ホームに戻る
出典 :
関連 :
目次 :
マルチバインディング
データバインディングにおいて、複数のプロパティをソースにとることができる機構。
これにより、
- 複数の string プロパティを連結して一つの TextBlock に表示する
- 複数の bool プロパティを参照し、コントロールの有効・無効を切り替える
といったことが可能となる。
但し複数の値を一つのターゲットに反映する都合上、コンバーターの実装が必須である。
実装例 : 複数の TextBox を参照し、いずれも空でない場合のみ Button を有効としたい
XAMLは要点を抜粋。

ウィンドウのXAML
<
Window x:Class=
"WpfApp1.MainWindow"
xmlns=
"http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x=
"http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d=
"http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc=
"http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local=
"clr-namespace:WpfApp1"
mc:Ignorable=
"d">
<!-- コンバーター -->
<
Window.Resources>
<
local:MyMultiStringConverter
x:Key=
"MyMultiStringConverter"/>
</
Window.Resources>
<!-- 画面表示 -->
<
Grid>
<!-- TextBox01 => Text を Text01 にバインド -->
<
TextBox Text=
"{Binding Path=Text01.Value}"/>
<!-- TextBox02 => Text を Text02 にバインド -->
<
TextBox Text=
"{Binding Path=Text02.Value}"/>
<!-- Button => IsEnabled を Text01 、Text02 の両方にバインド -->
<
Button>
<
Button.IsEnabled>
<!-- マルチバインディング -->
<!-- コンバーターを指定 -->
<MultiBinding Converter="{StaticResource ResourceKey=MyMultiStringConverter}">
<!-- values[0] -->
<Binding Path="Text01.Value"/>
<!-- values[1] -->
<Binding Path="Text02.Value"/>
</MultiBinding>
</
Button.IsEnabled>
</
Button>
</
Grid>
</
Window>
ウィンドウのコードビハインド
using System.Windows;
namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// ViewModel を DataContext に指定
DataContext = new ViewModel();
}
}
}
コンバーター
using System;
using System.Globalization;
using System.Windows.Data;
namespace WpfApp1
{
internal class MyMultiStringConverter : IMultiValueConverter
{
// 順変換(ソース ⇒ ターゲット)
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
string text01 = (string)values[0];
string text02 = (string)values[1];
// いずれもが空でなければ true を返す
return ( !String.IsNullOrEmpty(text01) ) && ( !String.IsNullOrEmpty(text02) );
}
// 逆変換(ターゲット ⇒ ソース)
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
// 逆変換は想定しないため未実装例外
throw new NotImplementedException();
}
}
}
ViewModel
using Reactive.Bindings;
namespace WpfApp1
{
class ViewModel
{
public ReactivePropertySlim<string> Text01 { get; } = new ReactivePropertySlim<string>();
public ReactivePropertySlim<string> Text02 { get; } = new ReactivePropertySlim<string>();
}
}
マルチバインディングにおけるコンバーターは、インタフェース IMultiValueConverter を実装して作成する( IValueConverter ではない)。
ソース値は Binding の記述順に values コレクションに束ねられる。
単一ソースの( IValueConverter を実装する)コンバーターとの違いは
- Convert() の第1引数が配列となっている
- ConvertBack() の第2引数と戻り値が配列となっている
である。ConvertBack() の第2引数が配列であることからもわかるように、複数のソースはそれぞれが異なる型であっても問題はない。